import re

import requests

from orm.session import get_session
from orm.entity import Mate


session = get_session()
domain = 'http://192.168.5.12:9096/emby'
item_name = '步兵'


def req_get(url, params=None):
    return requests.get(url=domain + url, params=params, headers={'X-Emby-Token': '48c8a4e16e134b95add48e853ffa4a2b'})


def get_title(_file_name: str) -> str:
    hey = re.compile(r'(heyzo)[-_](\d){4}', re.I)
    common = re.compile(r'(\d){5,6}[-_](\d){2,3}', re.I)
    hey_result = hey.search(_file_name)
    hey_common = common.search(_file_name)
    if hey_result:
        return hey_result.group()
    elif hey_common:
        return hey_common.group()
    else:
        return ''


if __name__ == "__main__":
    # 获取媒体库
    views = req_get('/Users/605a7bb5d1ce4f67a9a2c59f4cceed48/Views').json()['Items']
    parent_ids = [x['Id'] for x in views if item_name in x['Name']]
    uni_set = set()
    for parent_id in parent_ids:
        # 获取各个库下的电影
        items = req_get('/Users/605a7bb5d1ce4f67a9a2c59f4cceed48/Items', {'parentId': parent_id, 'Recursive': True, 'IncludeItemTypes': 'Movie'}).json()['Items']
        for item in items:
            # 获取每个电影的明细
            movie: dict = req_get('/Users/605a7bb5d1ce4f67a9a2c59f4cceed48/Items/{}'.format(item['Id'])).json()
            file_name = movie['FileName']
            # 番号
            # movie_name = re.search(r'[a-zA-Z]{3,6}-(\d){3,4}', file_name, flags=0).group()
            movie_name = get_title(file_name).upper()
            if movie_name in uni_set:
                continue
            uni_set.add(movie_name)
            # 是否破解
            mate = Mate(name=movie_name, state=2)
            mate.store_time_format(movie.get('DateCreated'))
            mate.release_date_format(movie.get('PremiereDate'))
            mate.suffix_format(file_name)
            session.add(mate)
            session.commit()
